package com.atguigu.reggie.controller;

import com.atguigu.reggie.common.R;
import com.atguigu.reggie.entity.Category;
import com.atguigu.reggie.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-10-11 17:22
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping()
    public R<String> save(@RequestBody Category category){
        log.info("category: {}",category);

        categoryService.save(category);

       return R.success("新增分类成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        // 分页构造器
        Page<Category> categoryPage = new Page<>(page,pageSize);

        // 条件构造器
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 添加排序条件，根据sort进行排序，若sort相同就跟据updateTime排序
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        // 进行分页查询
        categoryService.page(categoryPage,categoryLambdaQueryWrapper);

        return R.success(categoryPage);
    }

    /**
     * 根据id删除菜品或套餐分类
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id){
        log.info("删除分类,id为 ：{}",id);

        // 根据id删除
        categoryService.remove(id);

        return R.success("分类信息删除成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息：{}",category);

        // 直接修改
        categoryService.updateById(category);

        // 返回修改成功信息
        return R.success("修改分类信息成功");
    }

    /**
     *根据条件查询分类构造器
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        // 条件构造器
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 添加类别条件
        categoryLambdaQueryWrapper.eq(category.getType() != null,Category::getType,category.getType());

        // 添加排序条件
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        // 返回符合条件的list集合
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);

        return R.success(list);
    }
}
